class WorkerEventDispatcher {
  constructor() {
    this.workers = new Map()
    this.eventTarget = new EventTarget() //!
  }
  addWorker(name, scriptPath) {
    const worker = new Worker(scriptPath)
    worker.onmessage = (event) => { // 统一的消息处理 // 创建自定义事件
      const customEvent = new CustomEvent('workerMessage', { //!
        detail: { workerName: name, data: event.data }
      }) 
      this.eventTarget.dispatchEvent(customEvent) //! 分发事件
    }
    this.workers.set(name, worker)
    return worker
  }
  
  // 监听特定worker的消息
  onWorkerMessage(workerName, callback) {
    this.eventTarget.addEventListener('workerMessage', (event) => {
      if (event.detail.workerName === workerName) {
        callback(event.detail.data)
      }
    })
  }
  
  // 监听所有worker消息
  onAnyWorkerMessage(callback) {
    this.eventTarget.addEventListener('workerMessage', (event) => {
      callback(event.detail.workerName, event.detail.data)
    })
  }
}

// 使用示例
const dispatcher = new WorkerEventDispatcher()

// 添加worker
dispatcher.addWorker('worker1', './worker1.js')
dispatcher.addWorker('worker2', './worker2.js')

// 监听特定worker消息
dispatcher.onWorkerMessage('worker1', (data) => {
  console.log('worker1消息:', data)
})

dispatcher.onWorkerMessage('worker2', (data) => {
  console.log('worker2消息:', data)
})

// 监听所有worker消息
dispatcher.onAnyWorkerMessage((workerName, data) => {
  console.log(`${workerName} 发送了消息:`, data)
})